<?php

/*
 * Copyright (C) 2014 koodo@qq.com.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301  USA
 */

/**
 * Description of SqlFileCache
 *
 * @author Administrator
 */
class SqlCached extends Model {

    // 缓存5秒
    const EXP = 5;

    /**
     * 
     * @param type $k
     * @return type
     */
    private function genKey($k) {
        return hash('md4', $k . APPID . 'xa123d');
    }

    /**
     * 
     * @param type $k
     * @return type
     */
    public function get($k) {
        $fn = $this->genKey($k);
        $f = dirname(__FILE__) . DIRSEP . '..' . DIRSEP . 'tmp' . DIRSEP . 'sql_cache' . DIRSEP . $fn . '.sqlc';
        if (is_file($f) && (time() - filemtime($f)) < self::EXP) {
            return unserialize(base64_decode(file_get_contents($f)));
        } else {
            is_file($f) && unlink($f);
            return -1;
        }
    }

    /**
     * 
     * @param type $k
     * @param type $v
     * @return boolean
     */
    public function set($k, $v) {
        $fn = $this->genKey($k);
        $f = dirname(__FILE__) . DIRSEP . '..' . DIRSEP . 'tmp' . DIRSEP . 'sql_cache' . DIRSEP . $fn . '.sqlc';
        file_put_contents($f, base64_encode(serialize($v)));
        return true;
    }

}